package com.chg.mymvc.servlet;

import com.chg.mymvc.entity.User;
import com.chg.mymvc.service.UserServiceImpl;
import com.chg.mymvc.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        UserServiceImpl us = new UserServiceImpl();
        String name = req.getParameter("name");
//        User getuser = us.getUserByName(name);
//        if(getuser!=null){
//            resp.getWriter().write("ok");
//        }
//        else{
//            resp.getWriter().write("no");
//        }

        String password = req.getParameter("password");
        String mpassword = MD5Util.toMD5(password);
        System.out.println(mpassword+"passwor加密");
        System.out.println(mpassword.length()+"passwor加密长度");

        //用户输入的验证码
        String img = req.getParameter("checkimg");
        //图片出来的验证码
        String str = (String)req.getSession().getAttribute("sessionimg");
        //判断用户输入的验证码错误就让用户跳转到登陆页面 传一个参数即可
//        if(str.equalsIgnoreCase(img)){
//         resp.sendRedirect("main.html");
//
//        }
//        else{
//            resp.sendRedirect("login.html?a=5");
//            return;//如果验证码发生错误后面的代码都不用走了
//        }
        if(!Objects.equals(str,img)){
            resp.sendRedirect("login.html?a=5");
        }


else{
            User user = us.getUserByName(name);
            if(user==null){
                //用户名不存在
                resp.sendRedirect("login.html?a=1");
            }else{
                if(Objects.equals(mpassword,user.getPassword())) {
                    //登陆成功,并且把user对象存下
                    req.getSession().setAttribute("user",user);
                    resp.sendRedirect("main.html");

                }
                else{
                    resp.sendRedirect("login.html?a=2");
                }
        }


        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
